package util.concurrent;

import org.junit.Test;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class ConcurrentHashMap_ {

    @Test
    public void test0() {
        ConcurrentHashMap<String,String> map = new ConcurrentHashMap<>();
        String put1 = map.put("1", "1");//返回null 第一次更新成功
        String put2 = map.put("1", "2");//返回 1   返回老值
    }

    @Test
    public void test1() {
        ConcurrentHashMap<String,String> map = new ConcurrentHashMap<>();
        //IfAbsent 不存在则更新,存在则返回老值
        String s1 = map.putIfAbsent("1", "1");//第一次更新添加返回null
        String s2 = map.putIfAbsent("1", "2");//第二次返回old值,更新不成功
    }

    @Test
    public void test2() {
        //创建一个 HashMap
        HashMap<String, Integer> prices = new HashMap<>();

        // 往HashMap中添加映射项
        prices.put("1", 200);
        System.out.println("HashMap: " + prices);

        // 重新计算鞋子打了10%折扣后的值
        Integer newPrice = prices.compute("1", (key, value) -> value/2 );
        System.out.println(prices);
    }


   static ConcurrentHashMap<String,AtomicInteger> CACHE = new ConcurrentHashMap<>();

    public static AtomicInteger get(String key) {
        AtomicInteger val = CACHE.get(key);
        if (val != null) {
            return val;
        }
        AtomicInteger newVal = new AtomicInteger();
        AtomicInteger oldVal = CACHE.putIfAbsent(key, newVal);
        if (oldVal == null) {
            return newVal;//put成功
        }else {
            return oldVal;//不成功返回老值
        }
    }

    public static void main(String[] args) {
        System.out.println(get("1").hashCode());;
        System.out.println(get("1").hashCode());;
    }
}
